package top.jnaw.jee.platform.controller.basics.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.Approval;
import top.jnaw.jee.platform.model.Users;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Shiros;
import top.jnaw.jee.utils.Strings;

public class ApprovalController extends Controller {

  public void del() {
    ModelResult result = new ModelResult(Result.kModelDeleteError);
    JSONObject req = Strings.toJSONObject(this);
    JSONArray ids = Strings.getJSONArray(req, "ids", null);
    if (null != ids && ids.size() > 0) {
      for (int i = 0; i < ids.size(); i++) {
        if (Approval.delete(ids.getInteger(i))) {
          result.setResult(Result.kSuccess);
        }
      }
    }
    renderJson(result.toJson());
  }

  public void update() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);

    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    final int did = Strings.getInt(req, "did", Consts.DEFAULT_BAD_ID);
    final String status = Strings.getString(req, "status", "");
    final String content = Strings.getString(req, "content", "");
    final JSONArray accessory = Strings.getJSONArray(req, "accessory", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (null != user) ? user.getId() : -1;
    if (id > 0) {
      result = Approval.update(uid, id, status, content, accessory, did);
    }
    renderJson(result.toJson());
  }

  public void list() {
    JSONObject req = Strings.toJSONObject(this);
    final int page = Strings.getInt(req, "page", Consts.DEFAULT_PAGE);
    final int size = Strings.getInt(req, "size", Consts.DEFAULT_PAGE_SIZE);
    final JSONArray filter = Strings.getJSONArray(req, "filter", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (null != user) ? user.getId() : -1;
    renderJson(Strings
        .formatJsonDateTime(
            Strings.formatPage(Approval.list(page, size, filter))));
  }

  public void getPreviewId() {

    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);

    final int aid = Strings.getInt(req, "aid", Consts.DEFAULT_BAD_ID);
    final String type = Strings.getString(req, "type", "");

    if (aid > 0 && StrKit.notBlank(type)) {
      result = Approval.getPreviewId(aid, type);
    }

    renderJson(result.toJson());
  }
}
